package hanxx.security.filter;

import hanxx.common.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * edit:韩鑫鑫
 * 部门:产品研发三部
 * 用于同一线程下面
 **/
public class MapCacheUtils {
    private static ThreadLocal<Map<String,Object>> threadLocal = new ThreadLocal<>();

    public static void set(String key,Object object){
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotNull(object)){
            Map<String, Object> map = threadLocal.get();
            if (StringUtils.isNotNull(map)){
                map.put(key,object);
                threadLocal.set(map);
            } else {
                Map<String, Object> map1 = new HashMap<>();
                map1.put(key,object);
                threadLocal.set(map1);
            }
        } else {
            throw new RuntimeException("key或value值不可以为空");
        }
    }

    public static void set(Map<String,Object> map){
        if (StringUtils.isNotNull(map)){
            Map<String, Object> map1 = threadLocal.get();
            map1.putAll(map);
            threadLocal.set(map1);
        } else {
            throw new RuntimeException("map值不可以为空");
        }
    }

    public static Map<String,Object> get(){
        return threadLocal.get();
    }

    public static <T> T get(String key){
        if (StringUtils.isNotEmpty(key)){
            final Map<String, Object> map = threadLocal.get();
            if (StringUtils.isNotNull(map)){
                return (T) threadLocal.get().get(key);
            }
        }
        return null;
    }

    public static void remove(){
        threadLocal.remove();
    }
}
